/**
  ******************************************************************************
  * @file    bsp_iap_flash.c
  * @author  Iron
  * @date    2018-09-01
  * @version v1.0
  * @brief   bsp_iap_flash c file
  */

/** @addtogroup GROUP_BSP
  * @{
  */

/* includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "bsp_iap_flash.h"
#include "bsp_watchdog.h"

/* BEBUG LOG */
#include "debug_log.h"
#define LOG_LOCAL_LEVEL DBG_LOG_INFO  //  DBG_LOG_DEBUG DBG_LOG_INFO
DBG_LOG_TAG("BSP_IAP_FLASH");

/* private typedef -----------------------------------------------------------*/
/* private macro -------------------------------------------------------------*/
/* Base address of the Flash sectors */
#define BSP_MCU_FLASH_SECTOR_0     ((uint32_t)0x08000000) /* Base @ of Sector 0, 16 Kbyte */
#define BSP_MCU_FLASH_SECTOR_1     ((uint32_t)0x08004000) /* Base @ of Sector 1, 16 Kbyte */
#define BSP_MCU_FLASH_SECTOR_2     ((uint32_t)0x08008000) /* Base @ of Sector 2, 16 Kbyte */
#define BSP_MCU_FLASH_SECTOR_3     ((uint32_t)0x0800C000) /* Base @ of Sector 3, 16 Kbyte */
#define BSP_MCU_FLASH_SECTOR_4     ((uint32_t)0x08010000) /* Base @ of Sector 4, 64 Kbyte */
#define BSP_MCU_FLASH_SECTOR_5     ((uint32_t)0x08020000) /* Base @ of Sector 5, 128 Kbyte */
#define BSP_MCU_FLASH_SECTOR_6     ((uint32_t)0x08040000) /* Base @ of Sector 6, 128 Kbyte */
#define BSP_MCU_FLASH_SECTOR_7     ((uint32_t)0x08060000) /* Base @ of Sector 7, 128 Kbyte */
#define BSP_MCU_FLASH_SECTOR_8     ((uint32_t)0x08080000) /* Base @ of Sector 8, 128 Kbyte */
#define BSP_MCU_FLASH_SECTOR_9     ((uint32_t)0x080A0000) /* Base @ of Sector 9, 128 Kbyte */
#define BSP_MCU_FLASH_SECTOR_10    ((uint32_t)0x080C0000) /* Base @ of Sector 10, 128 Kbyte */
#define BSP_MCU_FLASH_SECTOR_11    ((uint32_t)0x080E0000) /* Base @ of Sector 11, 128 Kbyte */

/* Define bitmap representing user flash area that could be write protected (check restricted to pages 8-39). */
#define FLASH_SECTOR_TO_BE_PROTECTED (OB_WRP_SECTOR_0 | OB_WRP_SECTOR_1 | OB_WRP_SECTOR_2 | OB_WRP_SECTOR_3 |\
                                      OB_WRP_SECTOR_4 | OB_WRP_SECTOR_5 | OB_WRP_SECTOR_6 | OB_WRP_SECTOR_7 |\
                                      OB_WRP_SECTOR_8 | OB_WRP_SECTOR_9 | OB_WRP_SECTOR_10 | OB_WRP_SECTOR_11 )

/* private variables ---------------------------------------------------------*/
/* private function prototypes -----------------------------------------------*/
/* private functions ---------------------------------------------------------*/

/**
  * @brief  Gets the sector of a given address
  * @param  address: Flash address
  * @retval The sector of a given address
  */
static int32_t bsp_iap_flash_get_sector(uint32_t address)
{
    int32_t sector = -1;

    if ((address < BSP_MCU_FLASH_SECTOR_1) && (address >= BSP_MCU_FLASH_SECTOR_0))
    {
        sector = FLASH_SECTOR_0;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_2) && (address >= BSP_MCU_FLASH_SECTOR_1))
    {
        sector = FLASH_SECTOR_1;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_3) && (address >= BSP_MCU_FLASH_SECTOR_2))
    {
        sector = FLASH_SECTOR_2;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_4) && (address >= BSP_MCU_FLASH_SECTOR_3))
    {
        sector = FLASH_SECTOR_3;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_5) && (address >= BSP_MCU_FLASH_SECTOR_4))
    {
        sector = FLASH_SECTOR_4;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_6) && (address >= BSP_MCU_FLASH_SECTOR_5))
    {
        sector = FLASH_SECTOR_5;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_7) && (address >= BSP_MCU_FLASH_SECTOR_6))
    {
        sector = FLASH_SECTOR_6;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_8) && (address >= BSP_MCU_FLASH_SECTOR_7))
    {
        sector = FLASH_SECTOR_7;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_9) && (address >= BSP_MCU_FLASH_SECTOR_8))
    {
        sector = FLASH_SECTOR_8;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_10) && (address >= BSP_MCU_FLASH_SECTOR_9))
    {
        sector = FLASH_SECTOR_9;
    }
    else if ((address < BSP_MCU_FLASH_SECTOR_11) && (address >= BSP_MCU_FLASH_SECTOR_10))
    {
        sector = FLASH_SECTOR_10;
    }
    else     /*(address < FLASH_END_ADDR) && (address >= BSP_MCU_FLASH_SECTOR_11))*/
    {
        sector = FLASH_SECTOR_11;
    }

    return sector;
}

/**
  * @brief  Unlocks Flash for write access
  * @param  None
  * @retval None
  */
void bsp_iap_flash_init(void)
{
    DBG_LOGD(TAG, "iap flash init");

    /* Unlock the Flash to enable the flash control register access */
    HAL_FLASH_Unlock();
    /* Clear pending flags (if any) */
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
                           FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
}

void bsp_iap_flash_deinit(void)
{
    DBG_LOGD(TAG, "iap flash deinit");

    HAL_FLASH_Lock();
}

/**
  * @brief  This function does an erase of all user flash area
  * @retval 0: user flash area successfully erased
  *         1: error occurred
  */
uint32_t bsp_iap_flash_erase(uint32_t user_flash_start_address, uint32_t user_flash_size)
{
    int32_t res, i, start_sector, end_sector, sectors;
    uint32_t user_flash_end_address;
    uint32_t SectorError;
    FLASH_EraseInitTypeDef pEraseInit;

    DBG_LOGD(TAG, "iap flash erase addr=0x%08X, user_flash_size=%d", user_flash_start_address, user_flash_size);

    /* Get the sector where start the user flash area */
    user_flash_end_address = user_flash_start_address + user_flash_size;
    end_sector = bsp_iap_flash_get_sector(user_flash_end_address);
    start_sector = bsp_iap_flash_get_sector(user_flash_start_address);

    sectors = end_sector - start_sector + 1;

    DBG_LOGD(TAG, "iap flash erase start_sector:%d, end_sector:%d, sectors:%d.", start_sector, end_sector, sectors);

    /* Ref Datasheet, Sector (128 KB) erase time type 1.3s, max 2.6s. (MAX823 tWD (1.6s))*/
    bsp_watchdog_flash_earse_init();

    for (i = 0; i < sectors; i++)
    {
        bsp_watchdog_flash_earse_keepalive();

        pEraseInit.TypeErase = TYPEERASE_SECTORS;
        pEraseInit.Sector = start_sector + i;
        pEraseInit.NbSectors = 1;
        pEraseInit.VoltageRange = VOLTAGE_RANGE_3;

        res = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
        if (res != HAL_OK)
        {
            break;
        }
    }

    bsp_watchdog_flash_earse_deinit();

    return (res == HAL_OK) ? BSP_IAP_OK : BSP_IAP_ERASE_ERROR;
}

/**
  * @brief  This function writes a data buffer in flash (data are 32-bit aligned).
  * @note   After writing data buffer, the flash content is checked.
  * @param  FlashAddress: start address for writing data buffer
  * @param  Data: pointer on data buffer
  * @param  DataLength: length of data buffer (unit is 32-bit word)
  * @retval 0: Data successfully written to Flash memory
  *         1: Error occurred while writing data in Flash memory
  *         2: Written Data in flash memory is different from expected one
  */
uint32_t bsp_iap_flash_write(uint32_t flash_address, const uint8_t *data, uint32_t datalen)
{
    uint32_t i;

    if (data == NULL || datalen == 0)
    {
        return BSP_IAP_WRITING_ERROR;
    }

    // Word programming time type 16us.
    for (i = 0; ((datalen - i) > 4) && (flash_address <= (BSP_MCU_FLASH_END_ADDRESS - 4)); i += 4)
    {
        /* Device voltage range supposed to be [2.7V to 3.6V], the operation will be done by word */
        uint32_t word_data = *(uint32_t *)(data + i);
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, flash_address, word_data) != HAL_OK)
        {
            return BSP_IAP_WRITING_ERROR;        /* Error occurred while writing data in Flash memory */
        }
        if (*(uint32_t *)flash_address != word_data)
        {
            return BSP_IAP_WRITINGCTRL_ERROR;  /* Flash content doesn't match SRAM content */
        }
        flash_address += 4;
    }

    for (; (i < datalen)  && (flash_address <= (BSP_MCU_FLASH_END_ADDRESS - 4)); i++)
    {
        uint8_t byte_data = data[i];
        if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, flash_address, byte_data) != HAL_OK)
        {
            return BSP_IAP_WRITING_ERROR;        /* Error occurred while writing data in Flash memory */
        }
        if (*(uint8_t *)flash_address != byte_data)
        {
            return BSP_IAP_WRITINGCTRL_ERROR;  /* Flash content doesn't match SRAM content */
        }
        flash_address += 1;
    }

    return BSP_IAP_OK;
}


/**
  * @brief  Returns the write protection status of user flash area.
  * @param  None
  * @retval 0: No write protected sectors inside the user flash area
  *         1: Some sectors inside the user flash area are write protected
  */
uint16_t bsp_iap_flash_get_write_protection_status(void)
{
    uint32_t ProtectedSECTOR = 0xFFF;
    FLASH_OBProgramInitTypeDef OptionsBytesStruct;

    /* Unlock the Flash to enable the flash control register access *************/
    HAL_FLASH_Unlock();

    /* Check if there are write protected sectors inside the user flash area ****/
    HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);

    /* Lock the Flash to disable the flash control register access (recommended
       to protect the FLASH memory against possible unwanted operation) *********/
    HAL_FLASH_Lock();

    /* Get pages already write protected ****************************************/
    ProtectedSECTOR = ~(OptionsBytesStruct.WRPSector) & FLASH_SECTOR_TO_BE_PROTECTED;

    /* Check if desired pages are already write protected ***********************/
    if (ProtectedSECTOR != 0)
    {
        /* Some sectors inside the user flash area are write protected */
        return BSP_IAP_PROTECTION_WRPENABLED;
    }
    else
    {
        /* No write protected sectors inside the user flash area */
        return BSP_IAP_PROTECTION_NONE;
    }
}

/**
  * @brief  Configure the write protection status of user flash area.
  * @param  modifier DISABLE or ENABLE the protection
  * @retval HAL_StatusTypeDef HAL_OK if change is applied.
  */
int bsp_ipa_flash_write_protection_config(uint32_t modifier)
{
    uint32_t ProtectedSECTOR = 0xFFF;
    FLASH_OBProgramInitTypeDef config_new, config_old;
    HAL_StatusTypeDef result = HAL_OK;

    /* Get pages write protection status ****************************************/
    HAL_FLASHEx_OBGetConfig(&config_old);

    /* The parameter says whether we turn the protection on or off */
    config_new.WRPState = modifier;

    /* We want to modify only the Write protection */
    config_new.OptionType = OPTIONBYTE_WRP;

    /* No read protection, keep BOR and reset settings */
    config_new.RDPLevel = OB_RDP_LEVEL_0;
    config_new.USERConfig = config_old.USERConfig;
    /* Get pages already write protected ****************************************/
    ProtectedSECTOR = config_old.WRPSector | FLASH_SECTOR_TO_BE_PROTECTED;

    /* Unlock the Flash to enable the flash control register access *************/
    HAL_FLASH_Unlock();

    /* Unlock the Options Bytes *************************************************/
    HAL_FLASH_OB_Unlock();

    config_new.WRPSector    = ProtectedSECTOR;
    result = HAL_FLASHEx_OBProgram(&config_new);

    return result;
}

/**
  * @}
  */

/******************* (C)COPYRIGHT 2018 ***** END OF FILE *********************/
